package com.rytong.tools.ui;

import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.crypto.Base64;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.httpconnect.WaitDialog.Task;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.utils.AsyncImageLoader;
import com.rytong.tools.utils.AsyncImageLoader.ImageCallBack1;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.AbsoluteLayout.LayoutParams;

public class LPImageItem extends Component {

    // The image is which will be shown if this obj is focused.

    private boolean isHyperLink_;
    private String linkedUri_;

    private String descriptionText_;
    
    public AsyncImageLoader asyncImageLoader = null;
    public class MyLPImageItem extends TextView implements CompositedComponent {
    	
        public MyLPImageItem(Context context) {
            super(context);
            setFocusable(focusable());
            if(null == asyncImageLoader){
            	asyncImageLoader = Utils.getAsyncImageLoader();
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            boolean isAction = false;
            int xUp;
            int yUp;
            int touchEvent = event.getAction();
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                xDown_ = event.getX();
                yDown_ = event.getY();
                requestFocus();
                invalidate();
                // 必须点击有效果，否则无法激活按钮的弹起效果
                isAction = true;
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                // 预防控件出现连击效果
                long currentTime = System.currentTimeMillis();
                long timedifference = currentTime - LASTCLICKTIME;
                if (timedifference < 0) {
                    LASTCLICKTIME = currentTime;
                } else if (timedifference < jetLag_) {
                    LASTCLICKTIME = currentTime;
                    return false;
                } else {
                    LASTCLICKTIME = currentTime;
                }

                xUp = (int) event.getX();
                yUp = (int) event.getY();
                // 如果x或者y方向移动小于VALUE_个像素才判断为点击弹起，如果大于VALUE_个像素则判断为移动，不执行弹起效果
                if (Math.abs(xUp - xDown_) > offset_ || Math.abs(yUp - yDown_) > offset_) {
                    return false;
                }
                isAction = onClick((String) composited().property_.get("onclick"));
                invalidate();
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

        /**
         * @param canvas
         */
        private void drawImage(Canvas canvas) {
            Paint paint = getPaint();
            if (isFocused() && focusImg_ != null) {
                canvas.drawBitmap(focusImg_, getWidth() - unFocusImg_.getWidth() >> 1, 0, paint);
            } else {
                canvas.drawBitmap(unFocusImg_, (getWidth() - unFocusImg_.getWidth()) >> 1, 0, paint);
            }
        }

        /**
         * @param canvas
         */
        private void drawText(Canvas canvas) {
            if (descriptionText_ == null) {
                return;
            }
            String text = Utils.abbrevString(descriptionText_, paint_, width_);
            // 设置字体非抗锯齿效果，使字体边界更平滑
            float posX = (width_ - (int) paint_.measureText(descriptionText_)) >> 1;
            float posY = unFocusImg_.getHeight() + 20;
            canvas.drawText(text, posX, posY, paint_);
        }

        @Override
        public Component composited() {
            return LPImageItem.this;
        }

    }

    /**
     * @param url
     */
    public void setToLink(String url) {
        if (url != null) {
            setHyperLink(true);
            setLinkedUri(url);
            setFocusable(true);
        } else {
            setHyperLink(false);
            setLinkedUri(null);
            setFocusable(false);
        }
    }

    /**
     * 该方法主要用于指定控件的大小\显示颜色\样式等,如果服务端没有给定输出样式大小,则要自行计算一个合适的大小应用于该控件 Mould this component with its shape, color, size and
     * so on.
     * 
     * @return
     * @throws Exception
     *             TODO
     */
    public void mouldH() throws Exception {
        super.mouldH();
        MyLPImageItem mlpl = (MyLPImageItem) realView_;
        Paint paint = mlpl.getPaint();
        // 设置字体或者绘制效果平滑
        paint.setAntiAlias(true);
        if (null != cssStyle_) {
            String bgImageUrl = (String) cssStyle_.getProperty(CssStyle.BGIMAGEURL);
            if (null != bgImageUrl && !bgImageUrl.equals("")) {
                // 根据样式定义控件选中图片
                unFocusImg_ = Utils.getBitmapFromResources(getContext(), bgImageUrl);
                setLayoutFromURL();
                if (null != unFocusImg_) {
                    mlpl.setBackgroundDrawable(new BitmapDrawable(unFocusImg_));
                }
                // 用户点击的图片也应该有样式定义,此处暂时设置为未点击时的去色效果
                focusImg_ = Utils.getGrayBitmap(unFocusImg_);
            } else {
                setLayoutFromSRC();
            }
        } else {
            getImgFromSRC();
            if (null != unFocusImg_) {
                LayoutParams lp = (LayoutParams) getLayoutParams();
                lp.width = unFocusImg_.getWidth();
                lp.height = unFocusImg_.getHeight();
                setLayoutParams(lp);
            }
        }
    }

    /**
     * 从控件的src属性确定控件的图片和输出宽高
     */
    private void setLayoutFromSRC() {
        // TODO Auto-generated method stub
        getImgFromSRC();
        setLayoutFromURL();
    }

    /**
     * 从给定图片地址拿到的图片输出宽和高。
     */
    private void setLayoutFromURL() {
        if (null != unFocusImg_) {
            String w = fixedPX((String) cssStyle_.getProperty(CssStyle.WIDTH));
            String h = fixedPX((String) cssStyle_.getProperty(CssStyle.HEIGHT));
            float wi = 0;
            float hi = 0;
            if(!TextUtils.isEmpty(w)){
            	wi = Float.parseFloat(w);
            }
            if(!TextUtils.isEmpty(h)){
            	hi = Float.parseFloat(h);
            }
            if(wi != 0 && wi == hi){
            	wi = Utils.getScaledValueX(wi);
            	hi = wi;
            } else {
            	wi = Utils.getScaledValueX(wi);
            	hi = Utils.getScaledValueY(hi);
            }
            if (wi > 0 && hi > 0 && (wi != unFocusImg_.getWidth() || hi != unFocusImg_.getHeight())) {
                unFocusImg_ = Bitmap.createScaledBitmap(unFocusImg_, (int) wi, (int) hi, true);
            } else if (wi > 0 && hi <= 0 && wi != unFocusImg_.getWidth()) {
                hi = wi * unFocusImg_.getHeight() / unFocusImg_.getWidth();
                unFocusImg_ = Bitmap.createScaledBitmap(unFocusImg_, (int) wi, (int) hi, true);
            } else if (wi <= 0 && hi > 0 && hi != unFocusImg_.getHeight()) {
                wi = hi * unFocusImg_.getWidth() / unFocusImg_.getHeight();
                unFocusImg_ = Bitmap.createScaledBitmap(unFocusImg_, (int) wi, (int) hi, true);
            } else if (wi <= 0 && hi <= 0) {
                wi = unFocusImg_.getWidth();
                hi = unFocusImg_.getHeight();
            }
            LayoutParams lp = (LayoutParams) getLayoutParams();
            lp.width = (int) wi;
            lp.height = (int) hi;
            setLayoutParams(lp);
        }
    }

    /*
     * ************************************************************************
     * Set and Get methods. ************************************************************************
     */
    /**
     * @param isHyperLink
     *            the isHyperLink_ to set
     */
    public void setHyperLink(boolean isHyperLink) {
        isHyperLink_ = isHyperLink;
    }

    /**
     * @return the isHyperLink_
     */
    public boolean isHyperLink() {
        return isHyperLink_;
    }

    /**
     * @param linkedUri
     *            the linkAddr_ to set
     */
    public void setLinkedUri(String linkedUri) {
        linkedUri_ = linkedUri;
    }

    /**
     * @return the linkAddr_
     */
    public String linkedUri() {
        return linkedUri_;
    }

    /**
     * @param img
     */
    public void setImage(final Bitmap img) {
        unFocusImg_ = img;
    }

    /**
     * @param text
     */
    public void setDescriptionText(String text) {
        descriptionText_ = text;
    }

    /**
     * @param focusImage
     */
    void setFocusImage(Bitmap focusImage) {
        focusImg_ = focusImage;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPImageItem(activity);
    }

    /**
     * 从控件的src属性中读取图片信息
     */
    public void getImgFromSRC() {
        String imgUrl = (String) property_.get("src");
        if (null != imgUrl) {
            int width = width_, height = height_;
            if (imgUrl != null && imgUrl.contains("&w=") && imgUrl.contains("&h=")) {
                int indexW = imgUrl.indexOf("&w=");
                int indexH = imgUrl.indexOf("&h=");
                String w = imgUrl.substring((indexW + 3), indexH);
                String h = imgUrl.substring(indexH + 3);
                width = Integer.parseInt(w);
                height = Integer.parseInt((h));
            }
            if (imgUrl.startsWith("ewp_local")) {                
            	// 开启网络线程，下载图片.此处宽高有待讨论
                downloadImage(imgUrl, width, height);
            } else if (imgUrl.startsWith("http://")) {
                downloadImage(imgUrl, width, height);
            } else if(imgUrl.startsWith("local") || imgUrl.startsWith("/")){
                if(imgUrl.startsWith("local")){
                    // 引用本地图片
                    imgUrl = imgUrl.substring(imgUrl.indexOf("local:") + 6).trim();
                } else {
                    imgUrl = imgUrl.substring(1);
                }
                 
                unFocusImg_ = Utils.getBitmapFromResources(getContext(), imgUrl);
                if (null != unFocusImg_) {
                    realView_.setBackgroundDrawable(new BitmapDrawable(unFocusImg_));
                } 
            }
        }
    }

    /**
     * Download and cache thumbnail image in this POI.
     */
    public void downloadImage(final String imgUrl, final int width, final int height) {
        if (imgUrl != null) {
        	 WaitDialog wd = new WaitDialog();
        	 wd.addBgTask(new Task(0) {
        		 @Override
        		 public void run(WaitDialog dlg) throws Exception {
        			 // TODO Auto-generated method stub
        			 byte[] imageBytes = null;
        			 String url = imgUrl;
        			 /**
        			  * 下载图片的方法经过ewp，有加密和解密的过程，
        			  */
        			 if(imgUrl.indexOf("ewp_local") != -1 ){
        				 String hostAddress = Utils.getConfigStringFormAsset(getActivity(), "SERVER_URI");
        				 if(hostAddress.endsWith("/")){
        					 hostAddress = hostAddress.substring(0, hostAddress.length() - 1);
        				 }
        				 url = hostAddress + Utils.getConfigStringFormAsset(getActivity(), "GET_PIC_URI");
        				 String body;
        				 if(imgUrl.startsWith("url=")){
        					 body = Utils.escapeHTML(imgUrl);
        				 } else {
        					 body = Utils.escapeHTML("url=" + imgUrl);
        				 }
        				 
        				 try {
        					 String imageBody = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);
        					 HttpManager hm = new HttpManager(getActivity());
        					 Object image = hm.sendPostRequest(url, (Object) imageBody, null, null, null);
        					 
        					 if (image != null) {
        						 imageBytes = AESCipher.decrypt(Base64.decodeToBytes(image.toString()), 
        								 AESCipher.serverKey_,AESCipher.serverIv_);
        					 }
        					 
        					 unFocusImg_ = Utils.getBitmap(imageBytes);                             
        					 getActivity().runOnUiThread(new Runnable() {
        						 @Override
        						 public void run() {
        							 // TODO Auto-generated method stub
        							 realView_.setBackgroundDrawable(new BitmapDrawable(unFocusImg_));
        						 }
        					 });
        				 } catch (Exception e) {
        					 Utils.printException(e);
        				 }
        			 } else if(imgUrl.startsWith("http")){
        				 if(asyncImageLoader.cacheUtils.isInCache(imgUrl)){
        					 getActivity().runOnUiThread(new Runnable() {
        						 @Override
        						 public void run() {
        							 // TODO Auto-generated method stub
        							 realView_.setBackgroundDrawable(new BitmapDrawable(asyncImageLoader.getBitmapFromCache(imgUrl)));
        						 }
        					 });
        				 }else{
        					 final int resourceId = Utils.getResourcesId(getContext(), "img_waiting","drawable");
        					 if(resourceId > 0){
        	 					 getActivity().runOnUiThread(new Runnable() {
	        						 @Override
	        						 public void run() {
	        							 // TODO Auto-generated method stub
	        							 realView_.setBackgroundResource(resourceId);
	        						 }
	        					 });
        					 }
        					 asyncImageLoader.downloadImage(getContext(), imgUrl,new ImageCallBack1() {
								@Override
								public void loadImageSuccess(final Drawable drawable) {
									// TODO Auto-generated method stub
									if(null != drawable){
				    					 getActivity().runOnUiThread(new Runnable() {
			        						 @Override
			        						 public void run() {
			        							 // TODO Auto-generated method stub
			        							 realView_.setBackgroundDrawable(drawable);
			        						 }
			        					 });
									}
								}
							});
        				 }
        			 } else if (imgUrl.indexOf("http") == -1) {
        				 // 如果后台传过来的只是接口，则还需要作相应的补全地址操作
        				 url = imgUrl.concat(Utils.getConfigStringFormAsset(getActivity(), "SERVER_URI"));
        				 url = imgUrl.concat(Utils.getConfigStringFormAsset(getActivity(), "GET_PIC_URI"));
        			 }
        		 }
        	 });
         }
    }
    
    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	Utils.releaseObject(focusImg_);
    	Utils.releaseObject(unFocusImg_);
    }
}
